import SchemaMeta from './schema-meta';
import {
  isJSExpression,
  isJSFunction,
  isSimpleValue,
  transformStringToFunction,
  parseJSExpression,
} from '../utils/index';
import type { StateParserProps, StateParserConstructorProps, SourceCode, PackagesParserProps } from '../types';

export default class StateParser extends SchemaMeta implements StateParserProps {
  private packagesParser: PackagesParserProps;
  private state: SourceCode['state'];

  constructor(props: StateParserConstructorProps) {
    super(props);
    this.packagesParser = props.packagesParser;
  }

  async parse(): Promise<SourceCode['state']> {
    const schemaState = this.schema.state;
    if (schemaState) {
      this.state = Object.keys(schemaState).reduce<Required<SourceCode>['state']>((acc, key) => {
        const item = schemaState[key];
        if (isSimpleValue(item)) {
          acc[key] = item;
        } else if (isJSExpression(item)) {
          acc[key] = parseJSExpression(item.value);
        } else if (isJSFunction(item)) {
          acc[key] = transformStringToFunction(item.value);
        } else {
          acc[key] = '解析state值错误，没有匹配到这个类型的解析规则';
        }
        return acc;
      }, {});
      this.packagesParser.setPackages(5, {
        destructuring: true,
        subName: ['useInternalReducer'],
        packageName: './use-internal-reducer',
      });
    }
    return this.state;
  }
}
